import { sendMessage } from '@/utils/sub-rxjs-util'
import router from '@/router'
import { LocationQuery, RouteLocationRaw } from 'vue-router'
import { useCache } from '@/hooks/web/useCache'
import { CommonQianKunEnum } from './constants'

const { wsCache } = useCache()
import { name as packageName } from '../../package.json'
import { qiankunWindow } from 'vite-plugin-qiankun/es/helper'
const BASE_PREFIX = wsCache.get(CommonQianKunEnum.BASER_OUTE_PREFIX)

const findMetaByPath = (router, path) => {
  // 确保 path 以 / 开头（除非是相对路径）
  const normalizedPath = path.startsWith('/') ? path : `/${path}`;
  const matched = router.resolve(normalizedPath).matched;
  return matched.length > 0 ? matched[matched.length - 1].meta : null;
};

/**
 * 统一路由跳转方法 (适配 Qiankun 环境)
 *
 * @param location 路由位置，可以是字符串或路由对象
 * @param options 可选配置 { id: 标签页ID }
 * 
 * // 1. 基本用法（字符串路径）
    routePush('/home')

    // 2. 带查询参数
    routePush('/user?id=123')
    // 或
    routePush('/user', { param: { id: '123' } })

    // 3. 路由对象形式
    routePush({ path: '/report', query: { year: '2023' } })

    // 4. 指定标签页ID
    routePush('/dashboard', { id: 'my-dashboard' })

    // 5. 命名路由
    routePush({ name: 'UserProfile', params: { userId: 'abc' } })
 */
export function routePush(
  location: RouteLocationRaw | string,
  options?: {
    id?: string
    param?: LocationQuery
  }
): void {
  // 参数归一化处理
  const normalized = normalizeLocation(location, options?.param)
  const { path, query } = normalized
  const id = options?.id
  // Qiankun 环境下发送消息给主应用
  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
    sendToQiankun(path, query, id)
    return
  }
  // 非 Qiankun 环境下使用原始路由跳转
  router.push({ path: path, query: query })
}

/**
 * 发送消息给Qiankun主应用
 */
function sendToQiankun(path: string, query: LocationQuery = {}, id?: string) {
  //查找路由元信息
  const _path = path.split('?')[0]
  const metaInfo = findMetaByPath(router, _path)
  //生成标签页ID
  const generatedId = id ?? `${_path}`
  const pageMessage = {
    from: packageName,
    to: 'portal',
    operation: 'openTab',
    message: {
      type: 'id',
      id: generatedId,
      title: metaInfo?.title || '未命名标签页',
      content: '',
      sourceUrl: window.location.href,
      targetUrl: `${appendParam(path, query)}`,
      tabType: 'qiankun'
    }
  }

  console.debug('[Qiankun] Sending route message:', pageMessage)
  sendMessage(pageMessage)
  return pageMessage.message.id
}

/**
 * 标准化路由位置
 */
function normalizeLocation(
  location: RouteLocationRaw | string,
  extraQuery?: LocationQuery
): { path: string; query: LocationQuery } {
  let path = ''
  let query: LocationQuery = {}

  if (typeof location === 'string') {
    // 处理字符串路径
    const [basePath, queryString] = location.split('?')
    path = basePath
    if (queryString) {
      query = Object.fromEntries(new URLSearchParams(queryString).entries())
    }
  } else if ('path' in location) {
    // 处理路径对象
    path = location.path || ''
    query = { ...(location.query as LocationQuery) }
  } else {
    // 处理命名路由 - 需要解析
    const resolved = router.resolve(location)
    path = resolved.path.split('?')[0]
    query = resolved.query
  }

  // 合并额外参数
  if (extraQuery) {
    query = { ...query, ...extraQuery }
  }

  return { path, query }
}

/**
 * 工具函数：拼接路径和参数
 */
function appendParam(path: string, query?: LocationQuery): string {
  if (!query || Object.keys(query).length === 0) return path

  const queryString = new URLSearchParams()
  Object.entries(query).forEach(([key, value]) => {
    if (value !== undefined && value !== null) {
      queryString.append(key, String(value))
    }
  })

  return `${path}?${queryString.toString()}`
}

/**
 * qiankun环境关闭指定标签页
 * @param {关闭qiankun标签页} id
 */
export function closeTab(id) {
  const pageMessage = {
    from: packageName,
    to: 'portal',
    operation: 'closeTab',
    message: id
  }
  console.debug('[Qiankun] Sending close tab message:', pageMessage)
  sendMessage(pageMessage)
}

/**
 * qiankun环境关闭当前标签页
 */
export function closeCurrentTab() {
  const pageMessage = {
    from: packageName,
    to: 'portal',
    operation: 'closeTab',
    message: 'current'
  }
  console.debug('[Qiankun] Sending close tab message:', pageMessage)
  sendMessage(pageMessage)
}

/**
 * qiankun环境下从主应用访问子应用自己的静态文件需要统一处理
 * 方式：根据appIdentity补充前缀，同时配置nginx转发/{appIdentity}的请求至本子应用的静态文件
 * 示例：如appIdentity为 bm，那么对路径/static/ExampleFile/Import_Query_Example.xlsx的访问结果将变成/bm/static/ExampleFile/Import_Query_Example.xlsx
 *      此时对子应用静态文件访问将变为http:{主应用ip}:{主应用端口号}/bm/static/ExampleFile/Import_Query_Example.xlsx
 *      同时nginx需要如下配置。注意斜杠，格式需要严格一致
 *      location /{appIdentity} {
          proxy_pass http://{子应用ip}:{子应用端口}/;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
        }
 */
export function resolveStaticFilePath(path) {
  return apiConfig.web + '/' + path
}
